#include "filesystem.h"

using namespace bt;

void bt::InitFileSystem(char* argv0, const char* homeDir, const char* sysDir)
{
	FS_TRY(PHYSFS_init(argv0));		// Initialize PhysFS
	
	std::string userDir = PHYSFS_getUserDir();
	std::string homeDirPath = userDir + homeDir;

	// Try to make homeDir if it does not exist
	FS_TRY(PHYSFS_addToSearchPath(userDir.c_str(), 1));
	
	FS_TRY(PHYSFS_setWriteDir(userDir.c_str()));
	
	if(!PHYSFS_exists(homeDir))
	{
		PHYSFS_mkdir(homeDir);
		printf("Created settings directory: %s\n", homeDirPath.c_str());
	}
	
	FS_TRY(PHYSFS_removeFromSearchPath(userDir.c_str()));
	   
	// Add real search paths
	#ifndef WIN32
		FS_TRY(PHYSFS_addToSearchPath(sysDir, 1));
	#endif
	
	FS_TRY(PHYSFS_addToSearchPath(homeDirPath.c_str(), 1));
	
	FS_TRY(PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 1));
	
	// Setup for writing
	FS_TRY(PHYSFS_setWriteDir(homeDirPath.c_str()));
	
	// Initialize libXML
	LIBXML_TEST_VERSION
}

void bt::DeinitFileSystem()
{
	PHYSFS_deinit();
	
	xmlCleanupParser();
}

PHYSFS_sint64 bt::FS_readFile(Uint8*& buffer, const char* filename)
{
	PHYSFS_file* file = PHYSFS_openRead(filename);
	
	if(file)
	{
		PHYSFS_sint64 filesize = PHYSFS_fileLength(file);
		buffer = new Uint8[filesize];
		
		FS_TRY(PHYSFS_read(file, buffer, 1, filesize));
		PHYSFS_close(file);
		
		return filesize;
	}
	else
	{
		FS_LASTERROR;
		
		buffer = NULL;
		
		return NULL;
	}
}
